<?php

/**
* Класс для соединения с БД при регистрации пользователя
*/

class User_Data_Mapper
{
    
private $result = null;

    public function __construct(){}
    
     public function fetchUserInfo($userId)
    {
        $sel = mysql_connect (DB_HOST , DB_LOGIN, DB_PASSWORD);
        mysql_select_db(DB_NAME, $sel);
        mysql_query('SET NAMES UTF8');
        $sql1 = "   SELECT id, name, firstname, secondname, email
                    FROM users WHERE id='$userId'";
        $query = mysql_query($sql1) or die('DB Query Error');
        $row = mysql_fetch_array($query, MYSQL_ASSOC);
        $this->result = new User_Model($row);
        mysql_close($sel); 
        if ($this->result !== false){
            return $this->result;
        } else {
            return false; 
        }
         
    }    
    
    
    public function enterUser($login, $password)
    {
        $sel = mysql_connect (DB_HOST , DB_LOGIN, DB_PASSWORD);
        mysql_select_db(DB_NAME, $sel);
        mysql_query('SET NAMES UTF8');
        $sql = "SELECT id, name, rights FROM users WHERE name='$login' && password='$password' ";
        $query = mysql_query($sql);
        $row = mysql_fetch_array($query, MYSQL_ASSOC);
        if ($row !== false){
            $this->result = new User_Model($row);
            return $this->result;
        }
        mysql_close($sel);   
    }
 
 
 
    public function addUser($login, $firstname, $secondname, $email, $password)
    {
        $sel = mysql_connect (DB_HOST , DB_LOGIN, DB_PASSWORD);
        mysql_select_db(DB_NAME, $sel);
        mysql_query('SET NAMES UTF8');
        
        $sql = "SELECT name FROM users WHERE name='$login'";
        $query = mysql_query($sql);
        
        
        $this->result = mysql_fetch_array($query, MYSQL_NUM);
        if ($this->result[0] == $login) {
            mysql_close($sel);
            return false;
        }  else {
        $sql2 = "
            INSERT INTO users (name,firstname,secondname,email,password) 
            VALUES(
                    '$login',
                    '$firstname',
                    '$secondname',
                    '$email',
                    '$password')    
                    ";            
            if($query = mysql_query($sql2)) {
                // вопрос правильно ли сделано
                $middleRes =  $this->enterUser($login , $password);
                mysql_close($sel);
                return $middleRes;
                
            } 
        }     
    }   
}
